package com.zqcy.workbench.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import okhttp3.internal.Util;

import com.google.gson.Gson;
import com.onemdos.banner.OneMDOSBannerAction;
import com.onemdos.banner.listener.OneMDOSBannerDialogShowListener;
import com.onemdos.banner.protocol.advertsrv.ActivityMaterial;
import com.onemdos.base.permisson.BasePermission;
import com.onemdos.base.permisson.PermissionCallback;
import com.onemdos.configuration.MDOSConfiguration;
import com.onemdos.configuration.MDOSConfigurationCallback;
import com.onemdos.configuration.protocol.UpgradeRemoteConfigItemDetail;
import com.onemdos.location.MDOSLocation;
import com.onemdos.location.MDOSLocationListener;
import com.onemdos.location.OneMDOSLocationManagerProxy;
import com.onemdos.portal.config.PortalConfig;
import com.onemdos.portal.ui.fragment.HomepageFragment;
import com.onemdos.scan.ScanConstants;
import com.onemdos.scan.ScanUtils;
import com.onemdos.share.OneMDOSShareAPI;
import com.shinemo.base.core.utils.AppCommonUtils;
import com.shinemo.base.core.utils.CommonUtils;
import com.shinemo.base.core.utils.PermissionUtils;
import com.shinemo.base.core.utils.SharePrefsManager;
import com.shinemo.base.core.utils.ToastUtil;
import com.shinemo.mdoshotfix.HotFixCallback;
import com.shinemo.mdoshotfix.MDOSHotFix;
import com.shinemo.minisdk.config.MiniSdk;
import com.shinemo.minisdk.coreinterface.ApiCallback;
import com.shinemo.minisdk.fragment.MiniWebViewFragment;
import com.shinemo.minisdk.model.AppListOn;
import com.shinemo.minisdk.util.ColorUtils;
import com.shinemo.minisdk.util.IntentWrapper;
import com.shinemo.minisdk.util.Jsons;
import com.shinemo.tango.Patch;
import com.zqcy.workbench.R;
import com.zqcy.workbench.fragment.MainFragment;
import com.zqcy.workbench.fragment.MyFragment;
import com.zqcy.workbench.databinding.ActivityMainBinding;

import com.zqcy.workbench.hotfix.HotfixModifyClass;

import com.zqcy.workbench.utils.Constants;
import com.zqcy.workbench.utils.RxBus;
import com.zqcy.workbench.utils.Utils;
import com.zqcy.workbench.widget.FontIconTextView;

import java.io.File;
import java.util.List;

import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.shinemo.base.core.utils.Keys.DOWNLOAD_PATH;
import static com.shinemo.base.core.utils.Keys.MANAGE_ALL_FILES;
import static com.shinemo.base.core.utils.Keys.REQUEST_INSTALL;
import static com.shinemo.minisdk.util.Keys.APP_ID;
import static com.shinemo.minisdk.util.Keys.APP_SECRET;
import static com.shinemo.minisdk.util.Keys.EVENT;
import static com.shinemo.minisdk.util.Keys.EVENT_ON_LAUNCH;
import static com.shinemo.minisdk.util.Keys.EXTRAL_CREATE_TYPE;
import static com.shinemo.minisdk.util.Keys.LOADING_VIEW;
import static com.shinemo.minisdk.util.Keys.NAVIBAR;
import static com.shinemo.minisdk.util.Keys.NAVIBAR_COLOR;
import static com.shinemo.minisdk.util.Keys.NAVI_STYLE;
import static com.zqcy.workbench.utils.Constants.REQUEST_SCAN;

public class MainActivity extends AppCompatActivity {

    public static final String TAB_MAIN = "main";
    public static final String TAB_FINANCE = "finance";
    public static final String TAB_LIFE = "life";
    public static final String TAB_PROTAL = "portal";
    public static final String TAB_MY = "my";
    private ActivityMainBinding mBinding;

    private FontIconTextView[] fiViews;
    private String[] tabNames = new String[]{TAB_MAIN, TAB_FINANCE, TAB_PROTAL, TAB_MY};
    private String currentTabName = TAB_MAIN;


    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(mBinding.getRoot());
        Utils.fullScreen(this);
//        ColorUtils.setTransparent(this, Constants.isDarkModel, 1);

        initView();
        requestMini();
        initLocation();
    }

    /**
     * 获取定位 该功能可由开发者自行实现 本demo仅展示高德定位功能
     */
    private void initLocation() {
        OneMDOSLocationManagerProxy.getInstance().requestAMapLocation(this, new MDOSLocationListener() {
            @Override
            public void onLocationUpdate(MDOSLocation location) {
                RxBus.getInstance().post(location);
            }

            @Override
            public void onLocationFailed(String errorInfo) {
                Log.e("location", "定位失败" + errorInfo);
            }
        });
    }

    /**
     * 获取小程序配置的列表数据
     */
    private void requestMini() {
        MiniSdk.getMiniAppList("App837361644622315520", new ApiCallback<String>() {
            @Override
            public void onDataReceived(String data) {
                Log.e("tag", "getMiniAppList-> " + data);
                if (!TextUtils.isEmpty(data)) {
                    AppListOn appListOn = Jsons.fromJson(data, AppListOn.class);
                } else {
                    Log.e("tag", "request failed ");
                }

            }

            @Override
            public void onProgress(Object id, int progress) {

            }

            @Override
            public void onException(int code, String reason) {
                Log.e("tag", "onDataReceived-> code:" + code + " reason:" + reason);
            }
        });
    }

    private Bundle initPortalBundle(int portalId) {
        Bundle args = new Bundle();
        args.putLong("portal_id", portalId);
        return args;
    }

    private Bundle initBundle(int appId, String appSecret) {
        Bundle b = new Bundle();
        b.putInt(EXTRAL_CREATE_TYPE, 1);
        b.putString(EVENT, EVENT_ON_LAUNCH);
        b.putString(NAVIBAR, "");
        b.putString(NAVIBAR_COLOR, "");
        b.putInt(APP_ID, appId);
        b.putString(APP_SECRET, appSecret);
        b.putInt(NAVI_STYLE, 0);
        IntentWrapper.putExtra(b, LOADING_VIEW, (View) null);
        return b;
    }

    private void initView() {
        fiViews = new FontIconTextView[]{mBinding.fiMain, mBinding.fiFinance, mBinding.fiLife, mBinding.fiMy};
        mBinding.tabhost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_MAIN).setIndicator(TAB_MAIN), MainFragment.class, null);
        //小程序fragment 华为测试环境
//        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_FINANCE).setIndicator(TAB_FINANCE), MiniWebViewFragment.class, initBundle(75490399, "f41254ceff9c15947c07c0e1a5661032"));
        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_FINANCE).setIndicator(TAB_FINANCE), MiniWebViewFragment.class, initBundle(50370634, "8a8eb40af85f332ed8645d430208995b"));
        //小程序fragment 本地测试环境
//        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_FINANCE).setIndicator(TAB_FINANCE), MiniWebViewFragment.class, initBundle(93184599, "f4cc7d9d47024a1a81813d6d7c84c039"));
        //门户1
//        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_FINANCE).setIndicator(TAB_FINANCE), HomepageFragment.class, initPortalBundle(38));
        //门户2
//        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_PROTAL).setIndicator(TAB_PROTAL), HomepageFragment.class, initPortalBundle(38));
        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_PROTAL).setIndicator(TAB_PROTAL), HomepageFragment.class, initPortalBundle(79));
        mBinding.tabhost.addTab(mBinding.tabhost.newTabSpec(TAB_MY).setIndicator(TAB_MY), MyFragment.class, null);

        mBinding.fiMain.setOnClickListener(view -> selectTab(0));
        mBinding.fiFinance.setOnClickListener(view -> {
            selectTab(1);
        });
        mBinding.fiLife.setOnClickListener(view -> selectTab(2));
        mBinding.fiMy.setOnClickListener(view -> selectTab(3));
    }


    private void selectTab(int index) {
        if (index == 0 || index == 3) {
            Utils.fullScreen(this);
        } else {
            Utils.setColor(this, getResources().getColor(R.color.white));
        }
        if (index < 0 || index >= fiViews.length) return;
        String tabName = tabNames[index];
        if (currentTabName.equals(tabName)) return;
        currentTabName = tabName;

        for (FontIconTextView fiTextView : fiViews) {
            fiTextView.setIconTextColor(ContextCompat.getColor(this, R.color.c_gray5));
        }
        fiViews[index].setIconTextColor(ContextCompat.getColor(this, R.color.c_brand));
        mBinding.tabhost.setCurrentTabByTag(tabName);
    }

    /**
     * 扫码
     */
    public void scanCode(View view) {
        ScanUtils.startScanCode(MainActivity.this, REQUEST_SCAN);
    }

    /**
     * 收付款
     */
    public void PaymentCode(View view) {
        PaymentCodeActivity.startActivity(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case REQUEST_SCAN:
                if (data != null) {
                    String result = data.getStringExtra(ScanConstants.SCAN_RESULT);
                    if (!TextUtils.isEmpty(result)) {
                        new AlertDialog.Builder(MainActivity.this).setMessage(result).setCancelable(true).show();
                    } else {
                        ToastUtil.show(this, R.string.qr_code_fail);
                    }
                }
                break;
            case REQUEST_INSTALL:
                if (!TextUtils.isEmpty(SharePrefsManager.getInstance().getString(DOWNLOAD_PATH))) {
                    AppCommonUtils.startApkPermission(MainActivity.this, new File(SharePrefsManager.getInstance().getString(DOWNLOAD_PATH)));
                }
                break;
            case MANAGE_ALL_FILES:
                if (Environment.isExternalStorageManager()) {
                    Toast.makeText(this, "访问所有文件权限申请成功", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        OneMDOSShareAPI.onActivityForResult(requestCode, resultCode, data);
    }


    /**
     * 弹窗banner
     *
     * @param view
     */
    public void DialogBannerClick(View view) {
        try {
            new OneMDOSBannerAction(MainActivity.this).requestDialogBanner("index2").setListener(new OneMDOSBannerDialogShowListener() {
                @Override
                public void show(String viewCode) {
                    Log.e("DialogListener", "show");
                }

                @Override
                public void dismiss(String viewCode) {
                    Log.e("DialogListener", "dismiss");
                }

                @Override
                public void onAdClick(ActivityMaterial val) {
                    Log.e("DialogListener", "Ad click " + val);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void MiniClick(View view) {
        Log.e("Mini start", "MiniClick");
        MiniSdk.openMiniApp(this, 30584466, "78b15f79593410ef8359e70502a25595", "", 0);
    }

    /**
     * 门户跳转 直接调用该方法调入指定id的门户页面
     * 需要手动设置指定门户id的值
     *
     * @param view
     */
    public void PortalClick(View view) {
        Log.e("Portal start", "PortalClick");
        PortalConfig.getInstance().setPortalId(37);
        PortalConfig.getInstance().openPortal();
    }

    /**
     * 远程配置获取 (客户端仅做透传处理，数据的解析等后续业务操作请开发者自行接入)
     *
     * @param view
     */
    public void ConfigurationClick(View view) {
        MDOSConfiguration.getRemoteConfiguration(new MDOSConfigurationCallback() {
            @Override
            public void getRemoteList(List<UpgradeRemoteConfigItemDetail> list) {
                ToastUtil.show(MainActivity.this, getResources().getString(R.string.success_configuration));
                try {
//                    Log.e("configuration", "远程配置>> " + JSON.toJSONString(list));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void getNoRemote(int errorCode) {
                ToastUtil.show(MainActivity.this, getResources().getString(R.string.no_remote_configuration));
            }
        });
    }

    /**
     * 测试热修复，打印错误,模拟错误发生
     *
     * @param view
     */
    public void testHotFix(View view) {
//        ToastUtil.show(this, "error occur");
        HotfixModifyClass hotfixModifyClass = new HotfixModifyClass();
        hotfixModifyClass.testModify();
    }

    /**
     * 测试热修复，打印错误已解决，模拟热修复生效，打补丁包的时候把这个方法注释放开
     * 验证新增类的情况
     *
     * @param view
     */
//    @Modify
//    public void testHotFix(View view) {
//        HotFixAddClass.getInstance().test(); //在tango目录里面，可以直接拷过来
//    }
    public void loadPatch(View view) {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, MANAGE_EXTERNAL_STORAGE};
        } else {
            permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
        }
        new BasePermission(this).request(new PermissionCallback() {
            @Override
            public void onPermission(boolean granted) {
                if (!granted) {
                    PermissionUtils.testAllFiles(MainActivity.this);
                } else {
                    MDOSHotFix.loadPath(MainActivity.this, new HotFixCallback() {
                        @Override
                        public void onPatchApplied(boolean result, Patch patch) {
                            if (result) {
                                ToastUtil.show(MainActivity.this, "加载补丁成功");
                            }
                        }
                    });
                }
            }
        }, permissions);
    }

    public void testCrash(View view) {
        throw new NullPointerException();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OneMDOSLocationManagerProxy.getInstance().destroyLocation();
    }

    public void getDeviceId(View view) {
        ToastUtil.show(MainActivity.this, getResources().getString(R.string.device_only_id) + CommonUtils.getDeviceId(getApplicationContext()));
    }
}